package com.qianmi.cloud.service;

import com.qianmi.cloud.api.UserQueryProvider;
import com.qianmi.cloud.respone.SysUserResponse;
import com.qianmi.cloud.vo.Principal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Optional;

/**
 * @Description 用户信息
 * @Date: 1/16/22 17:27
 * @Created by xiaocai
 */
@Slf4j
@Primary
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserQueryProvider userQueryProvider;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserResponse user = userQueryProvider.loadUserByUsername(username);
        return getUser(user);
    }

    private UserDetails getUser(SysUserResponse user) {
        Optional.ofNullable(user).orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_ADMIN", "sys_menu_edit");
        return new Principal(user.getUsername(), "{bcrypt}" + user.getPassword(), authorities);
    }
}
